package io.github.quickmsg.interate.sharedstrategy;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.SafeConcurrentHashMap;
import org.apache.commons.lang3.tuple.ImmutableTriple;

import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;

public class StickyStrategy implements SharedStrategy{
    private final ConcurrentHashMap<Boolean, Integer> stickyIndex = new SafeConcurrentHashMap<>();
    @Override
    public ImmutableTriple<String, String, String> searchSharedSubscribe(Set<ImmutableTriple<String, String, String>> shareSubscribes, String consistentId) {
        List<ImmutableTriple<String, String, String>> subscribes = ListUtil.toList(shareSubscribes);
        int index = stickyIndex.computeIfAbsent(true, aBoolean -> randomIndex(subscribes));
        if(index >= subscribes.size()){
            index = stickyIndex.computeIfPresent(true, (aBoolean, integer) -> randomIndex(subscribes));
        }
        return subscribes.get(index);
    }

    private static int randomIndex(List<ImmutableTriple<String, String, String>> subscribes) {
        Random random = ThreadLocalRandom.current();
        int length = subscribes.size();
        return random.nextInt(length);
    }
}
